<script setup lang="ts">
import {
  defineEmits,
  defineProps,
  onMounted,
  ref,
  withDefaults,
  onUnmounted,
  Ref,
  toRef,
} from "vue";
import { NTime } from "naive-ui";

interface IPorps {
  time?: number; // 用于传递当前的时间值
  renderNode?: any; // 此节点渲染为
}
const props = withDefaults(defineProps<IPorps>(), {
  renderNode: "span",
});

let time: Ref<number> = ref(0);
// if (props.time) {
//   time = toRef(props, "time") as Ref<number>;
// } else {
//   time = ref(0);
// }

const emit = defineEmits<{
  (e: "update:time", param: number): void;
}>();

let start: number;
let timer: any;

onMounted(() => {
  start = Date.now();

  timer = setInterval(() => {
    time.value = Date.now() - start;
    // console.log(`[Stopwatch] `, time.value);
    emit("update:time", time.value);
  }, 500);
});

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <component :is="props.renderNode">
    <NTime :time="time" format="HH:mm:ss" time-zone="UTC" />
  </component>
</template>

<style scoped></style>
